import type { LoginInputContent } from './interface'
import type { UserInfoType, LoginRes } from '@/pages/login/api/interface'
import { makeAutoObservable } from 'mobx'
import { Toast } from 'antd-mobile'
import { RoleEnum } from '@/role'
import { history } from 'umi'
import * as Storage from '@/storage'
import wx from 'weixin-webview-jssdk'
export default class UserStore {
    private _loginInfo: LoginRes | null = null

    constructor() {
        makeAutoObservable(this)
        this._loadPageInit()
    }

    /**
     * 判断是否有 access_token
     */
    get isLogin() {
        return this._loginInfo !== null
    }

    /**
     * 获取 access_token
     */
    get getAccessToken() {
        return this._loginInfo?.token.access_token
    }

    /**
     * 获取 refresh_token
     */
    get getRefreshToken() {
        return this._loginInfo?.token.refresh_token
    }

    /**
     * 获取 角色信息
     */
    get getRoleInfo() {
        return this._loginInfo?.role_info
    }

    /**
     * 获取 当前用户拥有的角色
     */
    get getRoleArr() {
        return this._loginInfo?.role_arr
    }

    /**
     * 获取 组织信息
     */
    get getOrganInfo() {
        return this._loginInfo?.organ_info
    }

    /**
     * 获取 用户信息
     */
    get getUserInfo() {
        return this._loginInfo?.user_info
    }

    /**
     * 获取 登录页输入框的账号、密码
     */
    get getLoginInputContent(): LoginInputContent {
        return Storage.getLocalStorage('LOGIN_INPUT_CONTENT')
    }

    /** 是否是 部级中心角色 */
    get isCenterRole() {
        return RoleEnum.center === this.getRoleInfo?.role_id
    }

    /** 是否是 省级中心角色 */
    get isProvinceRole() {
        return RoleEnum.province === this.getRoleInfo?.role_id
    }

    /** 是否是 市级中心角色 */
    get isCityRole() {
        return RoleEnum.city === this.getRoleInfo?.role_id
    }

    /** 是否是 研修中心角色 */
    get isTrainerOrgan() {
        return RoleEnum.trainerOrgan === this.getRoleInfo?.role_id
    }

    /** 是否是 培训基地角色 */
    get isTrainerCompany() {
        return RoleEnum.trainerCompany === this.getRoleInfo?.role_id
    }

    /** 是否是 培训机构 */
    get isCompany() {
        return RoleEnum.company === this.getRoleInfo?.role_id
    }

    /** 是否是 培训师角色 */
    get isTeacherRole() {
        return RoleEnum.teacher === this.getRoleInfo?.role_id
    }

    /** 是否是 讲师角色 */
    get isTutor() {
        return RoleEnum.tutor === this.getRoleInfo?.role_id
    }

    /** 是否是 学员角色 */
    get isStudentRole() {
        return RoleEnum.student === this.getRoleInfo?.role_id
    }

    /** 是否是 管理员 */
    get isAdminRole() {
        return RoleEnum.admin === this.getRoleInfo?.role_id
    }

    /** 获取当前登录用户名 做权限区分 */
    get roleName() {
        const { getRoleInfo, getUserInfo, getOrganInfo } = this

        const nameMap: Record<RoleEnum, string | undefined> = {
            [RoleEnum.admin]: getRoleInfo?.name,
            [RoleEnum.center]: getRoleInfo?.name,

            [RoleEnum.student]: getUserInfo?.realname,
            [RoleEnum.teacher]: getUserInfo?.realname,
            [RoleEnum.tutor]: getUserInfo?.realname,

            [RoleEnum.province]: getOrganInfo?.name,
            [RoleEnum.city]: getOrganInfo?.name,
            [RoleEnum.trainerOrgan]: getOrganInfo?.name,
            [RoleEnum.trainerCompany]: getOrganInfo?.name,
            [RoleEnum.company]: getOrganInfo?.name,
        }

        const showName = getRoleInfo?.role_id ? nameMap[getRoleInfo.role_id] : '匿名用户'
        return showName
    }

    /**
     * 加载项目时初始化数据
     */
    private _loadPageInit = () => {
        if (Storage.hasLocalStorage('LOGIN_INFO')) {
            const _loginInfo = Storage.getLocalStorage('LOGIN_INFO')
            /** 把数组转成map */
            _loginInfo._permission = new Map(_loginInfo._permission)
            this._loginInfo = _loginInfo
        }
    }

    /**
     * 更新 accessToken
     * @param accessToken
     */
    updateAccessToken = (accessToken: string) => {
        this._loginInfo!.token.access_token = accessToken

        Storage.hasLocalStorage('LOGIN_INFO') &&
            Storage.setLocalStorage('LOGIN_INFO', this._loginInfo)
    }

    /**
     * 更新 用户信息
     * @param accessToken
     */
    updateUserInfo = (userInfo: UserInfoType) => {
        this._loginInfo!.user_info = userInfo
        Storage.hasLocalStorage('LOGIN_INFO') &&
            Storage.setLocalStorage('LOGIN_INFO', this._loginInfo)
    }

    /** 更新登录信息 */
    updateLoginInfo = (loginInfo: LoginRes) => {
        this._loginInfo = { ...this._loginInfo, ...loginInfo }
        Storage.setLocalStorage('LOGIN_INFO', this._loginInfo)
    }

    /**
     * 处理 登录数据
     * @param loginRes
     */
    handleLoginData = (loginRes: LoginRes) => {
        this._loginInfo = loginRes
        Storage.setLocalStorage('LOGIN_INFO', loginRes)

        if (window.__wxjs_environment !== 'miniprogram') {
            Toast.show('登录成功')
            history.push('/home')

            return
        }

        this.postMessage({
            type: 'login',
            loginRes,
        })
    }

    /**
     * 退出登录
     */
    logout = (showMsg: boolean = true) => {
        this._loginInfo = null
        Storage.delLocalStorage('LOGIN_INFO')
        if (window.__wxjs_environment !== 'miniprogram') {
            showMsg && Toast.show('退出成功')
            history.push('/login')

            return
        }

        this.postMessage({
            type: 'logout',
        })
    }

    postMessage = (data: any) => {
        wx.miniProgram.postMessage({
            data,
        })

        wx.miniProgram.redirectTo({
            url: '/pages/webViewPostMessage/index',
        })
    }
}
